<template name="home">
	<view>
		<view class="bg-green" :style="[{height:CustomBar + 'px','padding-top':StatusBar+'px'}]">
			<view class="head-top">
				<text>数字工厂首页</text>
			</view>
		</view>
		<!-- 中部应用宫格 -->
		<!-- <view class="bg-white" :style="{'padding-top':CustomBar+'px'}" v-if="showmiddleApps"> -->
		<view class="bg-white"  v-if="showmiddleApps">
			<view class="grid margin-bottom col-2 ">
				<navigator v-for="(item,index) in middleApps" :key="index" :url="'/pages/mcloud/' + item.name" class="nav-li"
				 navigateTo hover-class="none">
					<view class="flex align-center">
						<image :src="'/static/home/'+item.icon" mode="aspectFill" class="line2-icon"></image>
						<view class="text-df align-center">{{item.title}} <br /> <span class="text-light">{{item.text}}</span></view>
					</view>
				</navigator>
			</view>
		</view>
		<!-- <view class="grid  "> -->
		<!-- 轮播 -->
		<swiper class="screen-swiper square-dot " :indicator-dots="true" :circular="true" :autoplay="true" interval="5000"
		 duration="500" v-if="showGxChart">
			<swiper-item v-for="(item,index) in swiperList" :key="index">
				<!-- <image :src="item.url" mode="aspectFill" v-if="item.type=='image'"></image>
					<video :src="item.url" autoplay loop muted :show-play-btn="false" :controls="false" objectFit="cover" v-if="item.type=='video'"></video> -->
				<view class="qiun-bg-white qiun-title-bar qiun-common-mt">
					<view class="qiun-title-dot-light">工序产量</view>
				</view>
				<view class="qiun-charts">
					<canvas canvas-id="canvasColumn" id="canvasColumn" class="charts" disable-scroll=true @touchstart="touchColumngdzz"
					 @touchmove="moveColumn" @touchend="touchEndColumn"></canvas>
				</view>
				<!-- <view class="cu-tabbar-height"> -->
			</swiper-item>
		</swiper>
		<!-- 常用服务 -->
		<view class="cu-bar bg-white solid-bottom">
			<view class="action">
				<text class='cuIcon-title text-green'></text>常用功能
			</view>
		</view>
		<view class=" bg-white grid col-4 padding-sm">
			<view class="padding-sm " v-for="(item,index) in cMenu" :key="index" @tap="goPage(item.url)">
				<view class=" radius text-center shadow-blur">
					<!-- <image :src="item.icon"  mode="aspectFill" class="line2-icon"></image> -->
					<view class="cu-avatar df " :style="{backgroundImage: 'url(' + item.icon + ')'}">
						<!-- <view class="cu-tag badge" v-if="getTtemDotInfo(item)">{{getTtemDotInfo(item)}}</view> -->
					</view>
					<view class="text-df margin-top">{{item.name}}</view>
				</view>
			</view>
		</view>

		<view class="cu-tabbar-height">
		</view>
		<!-- </scroll-view> -->
	</view>
</template>

<script>
	import {
		pathToBase64,
		base64ToPath
	} from 'image-tools'
	import {
		hs,
		os
	} from '@/common/util/work.js'
	import uCharts from '@/sdk/u-charts/u-charts/u-charts.js';
	import {
		isJSON
	} from '@/common/checker.js';
	var _self;
	var canvaColumn = null;
	var canvaArea = null;
	var canvaLineA = null;
	var canvaRing = null;
	var canvaColumngdzz = null;
	var changeDatawdj = null;
	var canvaGauge = null;
	export default {
		name: 'home',
		props: {
			cur: String,
		},
		watch: {
			cur: {
				immediate: true,
				handler() {
					// console.log('watch', this.cur)
					this.initMenu()
				},
			},
		},
		data() {
			return {
				StatusBar: 20,
				CustomBar: 60,
				pixelRatio: 1,
				textarea: '',
				cWidth3: '', //圆弧进度图
				cHeight3: '', //圆弧进度图
				arcbarWidth: '', //圆弧进度图，进度条宽度,此设置可使各端宽度一致
				gdzxWidth: '',
				gdzxHeight: '',
				yhtWidth: '',
				yhtHeight: '',
				gdzzWidth: '',
				gdzzHeight: '',
				wdjWidth: '',
				wdjHeight: '',
				ybpWidth: '',
				ybpHeight: '',
				gaugeWidth: 15,
				type: 'default',
				swiperList: [{
						id: 1,
						type: 'image',
						url: '/static/banner/1.jpg',
						link: ''
					},
					// {id:2,type: 'image',url: '/static/banner/3.jpg', link: ''},
				],
				middleApps: [{
						icon: 'line2_icon1.png',
						title: '今日产量',
						'text': '0',
						'name': 'cltj'
					},
					{
						icon: 'line2_icon3.png',
						title: '今日合格率',
						'text': '100%',
						'name': 'passRate'
					},
				],
				// hsList: hs.data,
				// osList: os.data,
				cMenu: [],
				showmiddleApps: false,
				showChart: false,
				showGxChart: false,
				websock: '',
				heartCheck: null,
				lockReconnect: false,
				msgCount: 0,
				dot: {
					mailHome: false
				},
				chanlinagUrl: '/dcloud/sdReport/queryProductionProgressReport',
				passRateUrl: '/dcloud/sdReport/queryPassRateReport'
			}
		},

		created() {
			let that = this
			uni.getSystemInfo({
				success: function(e) {
					that.StatusBar = e.statusBarHeight;
					// #ifndef MP
					if (e.platform == 'android') {
						that.CustomBar = e.statusBarHeight + 50;
					} else {
						that.CustomBar = e.statusBarHeight + 45;
					};
					// #endif
					// #ifdef MP-WEIXIN
					let custom = wx.getMenuButtonBoundingClientRect();
					that.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
					// #endif
				}
			})
			// hs.data.forEach(item => {
			// 	pathToBase64(item.icon).then(base64 => {
			// 		this.$set(item, 'icon', base64)
			// 	}).catch(error => {
			// 	})
			// })
		},
		methods: {
			touchColumngdzz(e) {
				canvaColumngdzz.scrollStart(e);
			},
			moveColumn(e) {
				canvaColumngdzz.scroll(e);
			},
			touchEndColumn(e) {
				canvaColumngdzz.scrollEnd(e);
				canvaColumngdzz.touchLegend(e, {
					animation: true,
				});
				canvaColumngdzz.showToolTip(e, {
					format: function(item, category) {
						return category + ' ' + item.name + ':' + item.data
					}
				});
			},
			
			initMenu() {
				// this.initWebSocket();
				// this.loadCount(0);
				this.getChanliang();
				this.getPassRate();
				this.initChart();
				this.getMpMenu();
				// console.log(this.CustomBar)
			},
			getMpMenu() {
				//获取用户权限
				this.cMenu = []
				let username = uni.getStorageSync('login_user_info').username
				if (username == null || username == '') {
					return
				}
				this.$http.get('/dcloud/mpMenu/mpMenu/getMpMenu', {
					params: {
						username: username
					}
				}).then(res => {
					if (res.data.success) {
						let mpMenu = res.data.result
						mpMenu.forEach(item => {
							pathToBase64(item.icon).then(base64 => {
								this.$set(item, 'icon', base64)
							}).catch(error => {})
							if (item.common == "Y") {
								this.cMenu.push(item)
							}
							if (item.url == this.middleApps[0].name) {
								this.showmiddleApps = true
								this.showChart = true
							}
						})
						uni.setStorageSync("mpMenu", mpMenu)
					}
				}).catch(() => {
					// this.$tip.loaded();
					// this.$tip.error('获取系统权限失败')
				});
				//获取用户权限成功
			},
			initChart() {
				_self = this;
				this.cWidth3 = uni.upx2px(250); //这里要与样式的宽高对应
				this.cHeight3 = uni.upx2px(250); //这里要与样式的宽高对应
				this.arcbarWidth = uni.upx2px(24);
				// this.getServerDatajdt();
				// this.gdzxWidth = uni.upx2px(750);
				// this.gdzxHeight = uni.upx2px(500);
				// this.getServerDatagdzx();
				// this.yhtWidth = uni.upx2px(750);
				// this.yhtHeight = uni.upx2px(500);
				// this.getServerDatayht();
				this.gdzzWidth = uni.upx2px(750);
				this.gdzzHeight = uni.upx2px(500);
				this.getServerDatagdzz();
				// this.wdjWidth = uni.upx2px(750);
				// this.wdjHeight = uni.upx2px(500);
				// this.getServerDatawdj();
				// this.ybpWidth = uni.upx2px(750);
				// this.ybpHeight = uni.upx2px(500);
				// this.getServerDataybp();
			},
			getServerDatagdzz() {
				// let d = require('../../common/data.json');
				// uni.request({
				// 	url: 'https://mc.m-cloud.cc/mcloud/sys/randomImage/1',
				// 	data: {},
				// 	success: function(res) {
				// 		console.log(res.data.data)
				// 		res.data = d
				// 		console.log(d)
				// 		let Column = {
				// 			categories: [],
				// 			series: []
				// 		};
				// 		//这里我后台返回的是数组，所以用等于，如果您后台返回的是单条数据，需要push进去
				// 		Column.categories = res.data.data.LineA.categories;
				// 		Column.series = res.data.data.LineA.series;
				// 		_self.textarea = JSON.stringify(res.data.data.LineA);
				// 		_self.showColumngdzz("canvasColumn", Column);
				// 	},
				// 	fail: () => {
				// 		_self.tips = "网络错误，小程序端请检查合法域名";
				// 	},
				// });
				let that = this
				let url = '/sdReport/queryProductionProgressReport';
				this.$http.get(url, {
					params: {
						displayFlag: '0'
					}
				}).then(res => {
					if (res.data.success) {
						console.log(res.data.result)
						let Column = {
							categories: [],
							series: []
						};
						let s = {
							name: '',
							data: []
						}
						let max = 0;
						res.data.result.records.forEach(item => {
							Column.categories.push(item.vornrName);
							s.data.push(item.gmnga);
							if (item.gmnga > max) {
								max = item.gmnga
							}
						});
						Column.series[0] = s;

						_self.textarea = JSON.stringify(Column);
						setTimeout(function () {
						 _self.showColumngdzz("canvasColumn", Column, max);
						}, 200);
						

					}
				}).catch(err => {
					console.log(err);
				});
			},
			showColumngdzz(canvasId, chartData, max) {
				canvaColumngdzz = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'column',
					fontSize: 11,
					padding: [5, 15, 15, 15],
					legend: {
						show: true,
						position: 'top',
						float: 'center',
						itemGap: 30,
						padding: 5,
						margin: 5,
						//backgroundColor:'rgba(41,198,90,0.2)',
						//borderColor :'rgba(41,198,90,0.5)',
						borderWidth: 1
					},
					dataLabel: true,
					dataPointShape: true,
					background: '#FFFFFF',
					pixelRatio: _self.pixelRatio,
					categories: chartData.categories,
					series: chartData.series,
					animation: false,
					enableScroll: true,
					xAxis: {
						disableGrid: false,
						type: 'grid',
						gridType: 'dash',
						itemCount: 4,
						scrollShow: true,
						scrollAlign: 'left',
					},
					yAxis: {
						//disabled:true
						gridType: 'dash',
						splitNumber: 4,
						min: 1,
						max: max,
						format: (val) => {
							return val.toFixed(0)
						} //如不写此方法，Y轴刻度默认保留两位小数
					},
					width: _self.gdzzWidth * _self.pixelRatio,
					height: _self.gdzzHeight * _self.pixelRatio,
					extra: {
						column: {
							type: 'group',
							width: _self.gdzzWidth * _self.pixelRatio * 0.45 / chartData.categories.length
						}
					},
				});

			},
			goPage(page) {
				if (!page) {
					return false;
				}
				if (page === 'annotationList') {
					this.msgCount = 0
				}
				this.dot[page] = false
				this.$Router.push({
					name: page
				})
			},
			initWebSocket: function() {
				// WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
				var userId = this.$store.getters.userid;
				var url = this.$config.apiUrl.replace("https://", "wss://").replace("http://", "ws://") + "/websocket/" + userId;
				console.log('websocket url>>' + url);
				this.websock = new WebSocket(url);
				this.websock.onopen = this.websocketOnopen;
				this.websock.onerror = this.websocketOnerror;
				this.websock.onmessage = this.websocketOnmessage;
				this.websock.onclose = this.websocketOnclose;
			},
			websocketOnopen: function() {
				console.log("WebSocket连接成功");
				//心跳检测重置
				//this.heartCheck.reset().start();
			},
			websocketOnerror: function() {
				console.log("WebSocket连接发生错误");
				this.reconnect();
			},
			websocketOnmessage: function(e) {
				console.log("-----接收消息-------", e.data);
				var data = eval("(" + e.data + ")"); //解析对象
				if (data.cmd == "topic") {
					//系统通知
					this.loadCount('1')
				} else if (data.cmd == "user") {
					//用户消息
					this.loadCount('2')
				} else if (data.cmd == 'email') {
					this.loadEmailCount()
				}

				//心跳检测重置
				//this.heartCheck.reset().start();
			},
			websocketOnclose: function(e) {
				console.log("connection closed (" + e.code + ")");
				this.reconnect();
			},
			websocketSend(text) { // 数据发送
				try {
					this.websock.send(text);
				} catch (err) {
					console.log("send failed (" + err.code + ")");
				}
			},
			reconnect() {
				// var that = this;
				// if(that.lockReconnect) return;
				// that.lockReconnect = true;
				// //没连接上会一直重连，设置延迟避免请求过多
				// setTimeout(function () {
				//   console.info("尝试重连...");
				//   that.initWebSocket();
				//   that.lockReconnect = false;
				// }, 5000);
			},
			loadCount(flag) {
				console.log("loadCount::flag", flag)
				let url = '/sys/annountCement/listByUser';
				this.$http.get(url).then(res => {
					console.log("res::", res)
					if (res.data.success) {
						let msg1Count = res.data.result.anntMsgTotal;
						let msg2Count = res.data.result.sysMsgTotal;
						this.msgCount = msg1Count + msg2Count
						console.log("this.msgCount", this.msgCount)
					}
				})
			},
			loadEmailCount() {
				this.dot.mailHome = true
			},
			getTtemDotInfo(item) {
				if (item.page === 'annotationList' && this.msgCount > 0) {
					return this.msgCount
				}
				return '';
			},
			getChanliang() {
				this.$http.get(this.chanlinagUrl, {
					params: {
						displayFlag: '1'
					}
				}).then(res => {
					// console.log(res)
					if (res.data.success) {
						if(res.data.result.records.length!=0){
							this.middleApps[0].text = res.data.result.records[0].gmnga;
						}
						
						// let perArr = res.data.result
						//       let avatar=(perArr.avatar && perArr.avatar.length > 0)? api.getFileAccessHttpUrl(perArr.avatar):'/static/avatar_boy.png'
						// this.personalList.avatar =avatar

					}
				}).catch(err => {
					console.log(err);
				});
			},
			getPassRate() {
				this.$http.get(this.passRateUrl, {
					params: {
						displayFlag: '1'
					}
				}).then(res => {
					if (res.statusCode == "200") {
						this.middleApps[1].text = res.data.Line.series[0].data[6] + '%';
					}
				}).catch(err => {
					console.log(err);
				});
			},
		}
	}
</script>

<style scoped>
	/* .bg-blue{
		position: fixed;
		top:0;
		left:0;
		width: 100%;
		z-index: 100;
	} */
	.head-top {
		justify-content: center;
		align-items: center;
		display: flex;
		height: 100%;
	}

	.text-light {
		display: block;
		width: 100%;
		text-align: center;
	}

	.line2-icon {
		width: 60px;
		height: 60px;
	}

	.screen-swiper {
		min-height: 620upx;
	}

	.cu-avatar {
		background-position: center center;
		background-size: contain;
		background-repeat: no-repeat;
		background-color: transparent;
	}
</style>
